package org.atlantis.grosbeak.depot.proxy.value;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.atlantis.grosbeak.depot.DepotException;
import org.atlantis.grosbeak.depot.DepotMaker;
import org.atlantis.grosbeak.depot.desc.ValueDesc;
import org.atlantis.grosbeak.depot.proxy.ValueProxy;
import org.atlantis.grosbeak.lang.Exceptions;
import org.atlantis.grosbeak.lang.Pair;

/**
 * Map值代理。在配置文件中的格式应该是：“{name:'xxx', age:xxx}”，返回的是一个Map对象。
 * 
 * @author <a href="mailto:seenoevil.cn@gmail.com">SeeNoEvil</a>
 * 
 */
public class MapValueProxy implements ValueProxy {

	private Class<? extends Map<String, Object>> clazz;

	private List<Pair<ValueProxy>> pairs;

	public MapValueProxy(DepotMaker maker, Map<String, ValueDesc> map,
			Class<? extends Map<String, Object>> clazz) {
		this.clazz = clazz;
		pairs = new ArrayList<Pair<ValueProxy>>(map.size());
		for (Entry<String, ValueDesc> vd : map.entrySet()) {
			String key = vd.getKey();
			ValueDesc value = vd.getValue();
			pairs.add(new Pair<ValueProxy>(key, maker.makeValue(value)));
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.atlantis.grosbeak.depot.proxy.ValueProxy#get(org.atlantis.grosbeak
	 * .depot.DepotMaker)
	 */
	public Object get(DepotMaker maker) {
		try {
			Map<String, Object> map = clazz.newInstance();
			for (Pair<ValueProxy> vp : pairs) {
				map.put(vp.getKey(), vp.getValue().get(maker));
			}
			return map;
		} catch (Exception e) {
			throw Exceptions.wrapThrow(DepotException.class, e);
		}
	}
}
